<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .b1{
            margin-top: 20px;
            background-color: antiquewhite;
            width: 150px;
            height: 150px;
        }
        .b2{
            margin-top: 20px;
            /* width: 30px; */
            height: 300px;
            background-color: aqua;
        }
    </style>
</head>
<body>
    <button id="bt1">点击按钮修改样式</button>
    <div id="box" class="b1"></div>

    <script>
        //获取按钮和div
        let btn = document.getElementById('bt1');
        let box = document.getElementById('box');
       

        //给按钮绑定单击响应函数
        btn.addEventListener('click',()=>{


        // });
            // 一项一项修改
            // box.style.height = 300+'px';
            // box.style.backgroundColor = "yellow";
            // box.style.marginTop = 30 + 'px';

            //1.修改box的class类名
            // box.className = 'b2';
            
            //判断

            //2.添加b2 无则添加
            if(!hasClass(box,'b2')){
                addClass(box,'b2');
            };

            // 3.删除class
            // removeClass(box,'b2');
            
            //4.替换class
            // toggleClass(box,'b2');
            

        });
        
        //判断是否含有clsssname
        function hasClass(obj,cn){
            let reg = new RegExp("\\b" + cn + "\\b");
            return reg.test(obj.className);
            // alert(reg);
        }

        //添加class
        function addClass(obj,cn){
            // let reg = new RegExp("\\b" + cn + "\\b");
            obj.className += ' '+ cn;
        }

        //删除class
        function removeClass(obj,cn){
            let reg = new RegExp("\\b" + cn + "\\b");
            obj.className = obj.className.replace(reg,"");
        }

        //替换class
        function toggleClass(obj,cn){
            if(hasClass(obj,cn)){
                removeClass(obj,cn);
            }else{
                addClass(obj,cn);
            };
        }


    </script>


</body>
</html>